package com.uam.common.exception;


import com.mysql.cj.jdbc.exceptions.MysqlDataTruncation;
import com.uam.web.common.model.Result;
import com.uam.web.common.model.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author GoryLee
 * @Date 2022/11/15 20:26
 * @Version 1.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = CustomException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handler(CustomException customException) {
        log.error("运行时异常--------->:", customException);
        return Result.createError(customException.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handler(MethodArgumentNotValidException e) {
        log.error("校验异常--------->:", e);
        ObjectError objectError = e.getBindingResult().getAllErrors().stream().findFirst().orElse(null);
        return Result.createError(ResultCode.ILLEGAL_ARGUMENT.getCode(), objectError.getDefaultMessage());
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handler(IllegalArgumentException e) {
        log.error("Assert异常--------->", e);
        return Result.createError(e.getMessage());
    }

    @ExceptionHandler(value = UamException.class)
    public Result uamExceptionHandler(UamException uam) {
        return uam.getResult();
    }
    @ExceptionHandler(MysqlDataTruncation.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleMysqlDataTruncation(MysqlDataTruncation exception) {
        log.error("数据库数据截断错误: ", exception);
        return Result.createError("数据库错误,请联系管理员" );
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleGenericException(Exception exception) {
        log.error("系统异常: ", exception);
        String errorMessage = "服务器内部错误，请联系管理员";
        return Result.createError(errorMessage);
    }

}
